package org.elucid.gadmin.ui.events;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JFileChooser;

import org.elucid.gadmin.Utilities;
import org.elucid.gadmin.ui.GDialog;

/**
 * 
 * @author george
 *
 */
public class SaveActionListener implements ActionListener {

	private final GDialog gDialog;
	private boolean isSaveAs = false;

	public SaveActionListener(GDialog gDialog, boolean isSaveAs) {
		super();
		this.gDialog = gDialog;
		this.isSaveAs = isSaveAs;
	}

	public SaveActionListener(GDialog gDialog) {
		this.gDialog = gDialog;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		boolean doSave = false;
		
		if (gDialog.getFile() == null || isSaveAs ) {
			final JFileChooser fc = new JFileChooser();
			int returnVal = fc.showSaveDialog(gDialog);
			if (returnVal == 0) {
				gDialog.setFile(fc.getSelectedFile());
				doSave = true;
			}
		}
		else if( !isSaveAs )
		{
			doSave = true;
		}
		
		if( doSave )
		{
			gDialog.setTitle(gDialog.getFile().getName());

			try {
				String text = gDialog.getTextPane().getText();
				Utilities.writeToFile(text, gDialog.getFile());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
